package net.zjitc.yaobei_backed.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.zjitc.yaobei_backed.entity.User;
import net.zjitc.yaobei_backed.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @Author 董熠涛
 * @Date 2025/11/2 1:17
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userRepository.selectOne(queryWrapper);

        if (user == null) {
            System.out.println("UserDetailsService: User not found with username: " + username);
            throw new UsernameNotFoundException("User not found with username: " + username);
        }

        System.out.println("UserDetailsService: User found - username: " + user.getUsername());
        System.out.println("UserDetailsService: User password (from DB): " + (user.getPassword() != null ? user.getPassword() : "NULL"));
        
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            System.out.println("UserDetailsService: WARNING - User password is null or empty!");
        }

        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword() != null ? user.getPassword() : "")
                .authorities("USER")
                .build();
    }
}